package sf.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sf.database.dao.DBContext;
import sf.r2dbc.dao.R2dbcTemplate;
import sf.r2dbc.sql.R2dbcCrud;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class R2dbcLazyLoadUtils {
    private static final Logger logger = LoggerFactory.getLogger(R2dbcLazyLoadUtils.class);
    /**
     * 加载子对象,为了避免循环查询,当前暂时只支持一层查询.
     * @param client    client
     * @param object    对象
     * @param fieldName 级联字段
     */
    public static void loadCascadeObject(R2dbcTemplate client, DBContext context, DBObject object, String fieldName) {
        if (context != null) {
            context.setUseLazyLoad(false);
            client.useContext(context);
        }
        CountDownLatch latch = new CountDownLatch(1);
        client.monoFunc(connection -> R2dbcCrud.getInstance().getCrudModel().fetchLinks(connection, object, fieldName))
                .doFinally(signalType -> latch.countDown()).subscribe();
        try {
            if (!latch.await(30, TimeUnit.SECONDS)) {
                logger.error("waiting time out");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 设置延迟加载信息
     * @param object  对象
     * @param client  db对象
     * @param context 上下文 可为null
     */
    public static void setLazyLoadContext(DBObject object, R2dbcTemplate client, DBContext context) {
        object.lazyload = new R2dbcLazyLoadContext(client, context);
    }

    public static void setClient(R2dbcTemplate client, DBContext context) {
        context.getClient();
    }
}
